﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Json;
using System.Windows.Data;
using FeaturePlusInWeb.Model;
using FeaturePlusInWeb.Control;
using System.Collections.ObjectModel;
using System.Windows.Media.Imaging;
using System.Windows.Browser;

namespace FeaturePlusInWeb
{
    public partial class MainPage : UserControl
    {

        public MainPage()
        {
            InitializeComponent();

            LayoutRoot.MouseRightButtonDown += (sender, e) =>
            {
                e.Handled = true;
                //自己的菜单
            };

            LayoutRoot.MouseLeftButtonDown += (sender, e) =>
            {
                e.Handled = true;
                //自己的菜单
                treeContextMenu.Visibility = System.Windows.Visibility.Collapsed;
            };

            BindFirstLevelTree(0, treeView1.Items);

            if (Config.Xmode)
            {
                button1.Visibility = System.Windows.Visibility.Visible;
                button2.Visibility = System.Windows.Visibility.Visible;
                button3.Visibility = System.Windows.Visibility.Visible;
            }
            else {
                button1.Visibility = System.Windows.Visibility.Collapsed;
                button2.Visibility = System.Windows.Visibility.Collapsed;
                button3.Visibility = System.Windows.Visibility.Collapsed;
            }
        }

        /// <summary>
        /// 绑定树控件第一级
        /// </summary>
        protected void BindFirstLevelTree(int fid,ItemCollection nowitem)
        {
            string url = Config.UrlHead + "/featuredplus/getFeaturePlustTree.php?searchtype=fid&fid=" + fid.ToString() + "&datatype=IsRoof" + Config.UrlEnd;

            WebClient webGetTree = new WebClient();
            webGetTree.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webGetTree_DownloadStringCompleted);
            webGetTree.DownloadStringAsync(new Uri(url), nowitem);
        }

        void webGetTree_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            try
            {
                if (e.Result != null && e.Result != "" && e.Result != "null")
                {
                    ObservableCollection<FeaturedPlusTemplet> list = new ObservableCollection<FeaturedPlusTemplet>();
                    try
                    {
                        var jsonArray = JsonArray.Parse(e.Result);
                        foreach (JsonValue jsonValue in jsonArray)
                        {
                            var model = ObjectReflactor.PopulateEntityFromCollection<FeaturedPlusTemplet>(jsonValue);

                            list.Add(model);
                        }

                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("数据有错：" + ex.Message);
                        return;
                    }
                    ItemCollection nowitem = (ItemCollection)e.UserState;

                    nowitem.Clear();

                    foreach (var item in list)
                    {
                        TreeViewItem objTreeNode = new TreeViewItem();
                        objTreeNode.Header = item.Name;
                        objTreeNode.DataContext = item;
                        objTreeNode.IsExpanded = false;

                        if (item.Name != null)
                        {
                            nowitem.Add(objTreeNode);

                            objTreeNode.Loaded += new RoutedEventHandler(objTreeNode_Loaded);

                            //objTreeNode.MouseRightButtonUp += new MouseButtonEventHandler(objTreeNode_MouseRightButtonUp);

                            objTreeNode.Selected += new RoutedEventHandler(objTreeNode_Selected);


                        }
                    }
                    //treeView1.ItemsSource = list;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("读取数据失败！"+ex.Message);
            }
        }

        void objTreeNode_Selected(object sender, RoutedEventArgs e)
        {
            var objitem = (TreeViewItem)sender;

            var model = (FeaturedPlusTemplet)objitem.DataContext;
            BindListBoxAndImg(model);
        }

        /// <summary>
        /// 树节点被选中后的方法
        /// </summary>
        /// <param name="sender"></param>
        private void BindListBoxAndImg(FeaturedPlusTemplet model)
        {
            CurrentSelectFid = model.Id;
            CurrentSelectFKeyName = model.Keyname;

            BindFetureData(model.Id);

            if (model.Signpic != null && model.Signpic != "")
            {
                ImageSource ISource = new BitmapImage(new Uri(model.Signpic));

                image1.Source = ISource;

            }
            else
            {
                image1.Source = null;
            }
        }

        protected void BindFetureData(int fid)
        {
            string url = Config.UrlHead + "/featuredplus/getFeaturePlustTree.php?searchtype=fid&fid=" + fid.ToString() + Config.UrlEnd;

            WebClient webGetdata = new WebClient();
            webGetdata.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webGetdata_DownloadStringCompleted);
            webGetdata.DownloadStringAsync(new Uri(url));
        }


        /// <summary>
        /// 绑定右边的datagrid列表
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void webGetdata_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            if (e.Result != null && e.Result != "" && e.Result != "null")
            {
                try
                {
                    var jsonArray = JsonArray.Parse(e.Result);

                    ObservableCollection<FeaturedPlusTemplet> list = new ObservableCollection<FeaturedPlusTemplet>();

                    foreach (JsonValue jsonValue in jsonArray)
                    {
                        var model = ObjectReflactor.PopulateEntityFromCollection<FeaturedPlusTemplet>(jsonValue);

                        list.Add(model);
                    }

                    listBox1.ItemsSource = list;
                }
                catch (Exception ex)
                {
                    MessageBox.Show("数据有错："+ex.Message);
                    return;
                }
            }
            else
            {
                listBox1.ItemsSource = null;
            }
        }

        void objTreeNode_Loaded(object sender, RoutedEventArgs e)
        {
            var onoded = (TreeViewItem)sender;

            var mode = (FeaturedPlusTemplet)onoded.DataContext;

            BindFirstLevelTree(mode.Id, onoded.Items);
        }

        void objTreeNode_MouseRightButtonUp(object sender, MouseButtonEventArgs e)
        {
            var currentItem = ((TreeViewItem)sender);
            currentItem.IsSelected = true;

            var p = e.GetSafePosition(null);

            treeContextMenu.Margin = new Thickness(p.X, p.Y, 0, 0);

            treeContextMenu.Visibility = System.Windows.Visibility.Visible;
            treeContextMenu.DataContext = currentItem.DataContext;
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
        }

        void OKButton_Click(object sender, RoutedEventArgs e)
        {
        }

        private void LayoutRoot_Loaded(object sender, RoutedEventArgs e)
        {

        }

        private void button2_Click(object sender, RoutedEventArgs e)
        {

        }

        private void button3_Click(object sender, RoutedEventArgs e)
        {

        }

        private void button1_Click_1(object sender, RoutedEventArgs e)
        {

        }

        private void button1_Click_2(object sender, RoutedEventArgs e)
        {
            //CreateEditFPlus ce = new CreateEditFPlus();
            //ce.Show();
        }

        /// <summary>
        /// 被选中的目录
        /// </summary>
        int CurrentSelectFid = 0;

        /// <summary>
        /// 被选中的目录的名字
        /// </summary>
        string CurrentSelectFKeyName = string.Empty;

        /// <summary>
        /// 被选中的推荐位
        /// </summary>
        int CurrentSelectId = 0;


        /// <summary>
        /// 当前模版类型
        /// </summary>
        Config.SearchType CurrentSearchType
        {
            get;
            set;
        }

        private void Addtuijian()
        {
            treeContextMenu.Visibility = System.Windows.Visibility.Collapsed;

            int fid = CurrentSelectFid;

            CreateEditFPlus c = new CreateEditFPlus(fid, true);

            //这个名字只在创建的时候有
            c.FKeyName = CurrentSelectFKeyName;

            c.Closed += new EventHandler(c_Closed);

            c.Show();
        }

        void c_Closed(object sender, EventArgs e)
        {
            
            if (((CreateEditFPlus)sender).DialogResult == true)
            {
                //重新绑定数据

                if (treeView1.SelectedItem != null)
                {
                    var model = (FeaturedPlusTemplet)((TreeViewItem)treeView1.SelectedItem).DataContext;

                    BindListBoxAndImg(model);
                }

                
            }
        }

        private void button1_Click_3(object sender, RoutedEventArgs e)
        {
            BindFirstLevelTree(0,treeView1.Items);
        }

        private void Edittuijian(int fid)
        {
            if (fid != 0)
            {
                treeContextMenu.Visibility = System.Windows.Visibility.Collapsed;
                CreateEditFPlus c = new CreateEditFPlus(fid, false);
                c.FKeyName = "";//设置上级名称为空，主要是修改的时候，不用再管这个上级名称
                c.Closed += new EventHandler(c_Closed);

                c.Show();
            }
            else
            {
                MessageBox.Show("请选择一个推荐位来修改！");
            }
        }

        /// <summary>
        /// 创建推荐位
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click_4(object sender, RoutedEventArgs e)
        {
            Addtuijian();
        }

        private void button2_Click_1(object sender, RoutedEventArgs e)
        {
            Edittuijian(CurrentSelectFid);
        }

        private void button3_Click_1(object sender, RoutedEventArgs e)
        {
            Edittuijian(CurrentSelectId);
        }

        FeaturedPlusCtl _fc;


        /// <summary>
        /// 选中listbox某项后
        /// </summary>
        protected void ShowListBoxItem()
        {
            if (listBox1.SelectedItem != null)
            {
                var model = (FeaturedPlusTemplet)listBox1.SelectedItem;
                CurrentSelectId = model.Id;

                CurrentSearchType = (Config.SearchType)Enum.Parse(typeof(Config.SearchType), model.Datatype, false);

                //ImageSource s = ImageSource.
                if (model.Signpic != null && model.Signpic != "")
                {
                    ImageSource ISource = new BitmapImage(new Uri(model.Signpic));

                    image1.Source = ISource;

                }
                else
                {
                    image1.Source = null;
                }

            }
            else
            {
                image1.Source = null;
            }
        }


        /// <summary>
        /// 推数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button4_Click(object sender, RoutedEventArgs e)
        {
            if (CurrentSearchType == Config.SearchType.StaticBlock)
            {
                ChangeStaticBlockTempleteData cd = new ChangeStaticBlockTempleteData(CurrentSelectId);

                cd.textBox1.Text = HttpUtility.HtmlDecode(((FeaturedPlusTemplet)listBox1.SelectedItem).Htmlshow);

                cd.Closed += new EventHandler(cd_Closed);

                cd.Show();
            }
            else
            {

                if (_fc == null)
                {
                    _fc = new FeaturedPlusCtl();
                    secondGrid.Children.Add(_fc);
                    _fc.OnClose += new ControlChangedEventHandler(_fc_OnClose);
                    _fc.OnShow += new ControlChangedEventHandler(_fc_OnShow);
                }
                _fc.FeaturedPlusId = CurrentSelectId;
                _fc.SearchType = CurrentSearchType;
                _fc.Margin = new Thickness(0, 0, 0, 0);
                _fc.Show();
            }
        }

        void cd_Closed(object sender, EventArgs e)
        {
            //重新绑定数据

            var c = (ChildWindow)sender;

            if (c.DialogResult == true)
            {

                if (treeView1.SelectedItem != null)
                {
                    var model = (FeaturedPlusTemplet)((TreeViewItem)treeView1.SelectedItem).DataContext;

                    BindListBoxAndImg(model);
                }
            }

        }

        void _fc_OnShow(object sender)
        {
            secondGrid.Visibility = System.Windows.Visibility.Visible;
            boderIndx.Visibility = System.Windows.Visibility.Visible;
        }

        void _fc_OnClose(object sender)
        {
            secondGrid.Visibility = System.Windows.Visibility.Collapsed;
            boderIndx.Visibility = System.Windows.Visibility.Collapsed;
        }

        private void listBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ShowListBoxItem();
        }
    }
}
